package com.boot2.core.constant;

import com.boot2.core.exception.BusinessException;
import com.boot2.core.utils.ThreadPoolTaskExecutorUtil;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhangweilin
 * @description:线程池跟踪
 * @date 2018/6/12
 */
public class ThreadPoolTaskExecutorContant {
    /**
     * 将大任务拆分多批次任务，每个批次任务，用线程池执行，多次的定时调度，复用线程池，
     */
    private final static Map<String, ThreadPoolTaskExecutor> threadPoolTaskExecutorMap = new ConcurrentHashMap<>();

    /**
     * 通过key获取
     *
     * @param key 此key同时也是线程池的ThreadNamePrefix
     * @return
     */
    public static ThreadPoolTaskExecutor getThreadPoolTaskExecutor(String key) {
        if (!threadPoolTaskExecutorMap.containsKey(key)) {
            throw new BusinessException("没有名为【" + key + "】的线程池");
        }
        return getThreadPoolTaskExecutor(key, 0.5);
    }

    /**
     * 通过key获取
     *
     * @param key      此key同时也是线程池的ThreadNamePrefix
     * @param cpuScale cpu等待与忙碌比例
     * @return
     */
    public static ThreadPoolTaskExecutor getThreadPoolTaskExecutor(String key, double cpuScale) {
        if (threadPoolTaskExecutorMap.containsKey(key)) {
            return threadPoolTaskExecutorMap.get(key);
        }
        ThreadPoolTaskExecutor threadPoolTaskExecutor = ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor(cpuScale);
//        ThreadPoolTaskExecutor threadPoolTaskExecutor = ThreadPoolTaskExecutorUtil.createThreadPoolTaskExecutor(0.5);
        threadPoolTaskExecutor.setThreadNamePrefix(key);
        threadPoolTaskExecutorMap.put(key, threadPoolTaskExecutor);
        return threadPoolTaskExecutor;
    }
}
